package com.zmn.oms.dubbo.impl.normal.order;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.business.interfaces.work.tag.OrderTagBService;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.dto.OmsOperator;
import com.zmn.oms.dubbo.dto.common.work.OrderLogAddDIO;
import com.zmn.oms.dubbo.interfaces.normal.order.OrderLogModifyRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.entity.log.OrderLog;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.aop.OrderWorkLogUtils;
import lombok.extern.log4j.Log4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.Valid;

/**
 * @author sunlife
 * @date:2021/7/2 4:28 下午
 * description:
 */
@Log4j
@Service(loadbalance = "roundrobin", timeout = 10000, retries = 0, version = DubboConsts.INTERFACE_VERSION, validation = "true")
public class OrderLogModifyRemoteServiceImpl implements OrderLogModifyRemoteService {

    @Autowired
    OrderLogBService orderLogBService;
    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderTagBService orderTagBService;


    @Override
    public ResponseDTO add(@Valid OrderLogAddDIO addDIO) {
        try {
            OrderWork orderWork = orderWorkService.findOrderWorkByKey(addDIO.getOrderId(), addDIO.getWorkId());

            OmsOperator operator = BeanMapper.map(addDIO, OmsOperator.class);

            OrderLog orderLog = BeanMapper.map(addDIO, OrderLog.class);

            orderLog.setTypeName(OrderLogConsts.getOrderLogTypeName(orderLog.getType()));
            OrderWorkLogUtils.processOrderLogOperater(orderLog, operator);
            OrderWorkLogUtils.processOrderLogStatus(orderLog, orderWork, operator);

            orderLog.setOperatorTypeName(GlobalConsts.getOperatorTypeName(addDIO.getOperatorType()));
            orderLog.setCreateTime(DateUtil.getNow());
            orderLogBService.save(orderLog);

            // 日志类型是否生成订单标签
            orderTagBService.sendOrderTagMq(addDIO.getOrderId(), addDIO.getWorkId(), addDIO.getType());
        } catch (Exception e) {
            log.error("添加订单日志失败", e);
            return ResponseDTO.fail("添加订单日志失败");
        }


        return ResponseDTO.success();
    }
}
